<?php

namespace Modules\Production\Repository;


use App\Services\InventoryService;
use App\Services\KingDeeService;
use Modules\Production\Models\ProductionOrder;
use Modules\Production\Models\ProductionOrderDetail;
use Modules\Production\Models\ProductionReportOrder;

class StockTaskRepository
{

    /**
     * 金蝶备货预留查询
     * @param $docno 单据号
     * @param $fnumber 物料编码
     * @return array
     * @throws \Exception
     */
    static public function kingdeeStock($docno,$fnumber){

        $kindee = new KingDeeService();

        $stock = $kindee->form('TVJB_DJYLYKCCX')
            ->field('F_TVJB_SKU.FNUMBER,F_TVJB_YLSL,F_TVJB_KYKCSL,F_TVJB_SCYLQDDH,F_TVJB_SKU,F_TVJB_YLQDYLCK,F_TVJB_KCSL,F_TVJB_YLSL,F_TVJB_YLQDYLSL,F_TVJB_KCCK.FNUMBER,F_TVJB_KCCK.FNAME')
            ->where('F_TVJB_SCYLQDDH',$docno)
            ->where('F_TVJB_SKU.fnumber',$fnumber)
            ->ExecuteBillQuery();

        if(empty($stock)) {
            return $stock;
        }

        $backInv = [];
        foreach ($stock as $val){
            $groupIndex = trim($val['F_TVJB_SKU.FNUMBER']) . trim($val['F_TVJB_SCYLQDDH']) . trim($val['F_TVJB_KCCK.FNUMBER']);

            if(!isset($backInv[$groupIndex])){
                $backInv[$groupIndex] = [
                    'material_no'   => $val['F_TVJB_SKU.FNUMBER'],
                    'wms_name'      => $val['F_TVJB_KCCK.FNAME'],
                    'qty'           => $val['F_TVJB_KCSL'],
                    'reserve_qty'   => $val['F_TVJB_YLSL'],
                    'canuse_qty'    => $val['F_TVJB_KYKCSL'],
                    'grant_qty'   => $val['F_TVJB_KYKCSL'],
                ];
            }else{
                $backInv[$groupIndex]['qty'] += $val['F_TVJB_KCSL'];
                $backInv[$groupIndex]['reserve_qty'] += $val['F_TVJB_YLSL'];
                $backInv[$groupIndex]['canuse_qty'] += $val['F_TVJB_KYKCSL'];
                $backInv[$groupIndex]['grant_qty'] += $val['F_TVJB_KYKCSL'];
            }
        }

        return array_values($backInv);

    }

    /**
     * 备货库存查询
     * @param $fnumber
     * @return mixed
     */
    static public function stockInv($docno,$fnumber){

        $production = ProductionOrderRepository::getIdByDocno($docno);

        $inv = InventoryService::getInventoryByMaterial($fnumber,$production->fowneridsety_number,$production->fprdorgid_number)->toArray();

        $stockList = [];
        foreach ($inv as &$val){

            $val['scan_count'] = StockTaskScanRepository::getScanCountByLotnum($production->id,$val['material_no'],$val['lot_num'],$val['location']);
            if( ($val['qty'] - $val['assign_qty'] - $val['lock_qty']) > 0){
                $stockList[] = $val;
            }
        }
        return $stockList;
    }

}
